package servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "Demo6_CookieLoginServlet", value = "/cookieLogin")
public class Demo6_CookieLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = "";
        String password = "";

        //1.获取用户浏览器中的所有Cookie存储的数据
        Cookie[] cookies = request.getCookies();

        //2.如果有cookie信息，进行遍历
        if(null!=cookies && cookies.length>0){
            for (Cookie cookie : cookies) {
                //3.获取cookie的 key 也就是名字
                String cookieName = cookie.getName();
                if(null!=cookieName && cookieName.equals("username")){
                    username = cookie.getValue();
                } else if (null!=cookieName && cookieName.equals("password")) {
                    password = cookie.getValue();
                }
            }
        }

        //4.1 如果从cookie中没有获取到 username 的数据，需要从页面的文本框中获取username
        if(null!=username && username.equals("")){
            username = request.getParameter("username");
        }
        //4.1 如果从cookie中没有获取到 password 的数据，需要从页面的文本框中获取password
        if(null!=password && password.equals("")){
            password = request.getParameter("password");
        }

        //5.不管是从cookie中还是从文本框中获取的用户名密码 都用来判断数据是否正确
        if(username.equals("tiger") && password.equals("scott")){

            //6.1 如果登录成功，把用户名和密码创建成Cookie对象
            Cookie cookie_username = new Cookie("username",username);
            Cookie cookie_password = new Cookie("password",password);

            //6.2 设置每个Cookie的生命周期  -1表示浏览器关闭即失效  如果是正整数表示保存的时间长度，内容是存在客户端本地磁盘，时间到自动失效
            cookie_password.setMaxAge(-1);
            cookie_username.setMaxAge(10*24*3600);

            //6.3 把Cookie对象存入到浏览器的Cookie中
            response.addCookie(cookie_username);
            response.addCookie(cookie_password);

            //如果用户名和密码都正确，提示登录成功
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();

            writer.print("<html>" +
                    "<head><title>登录结果</title></head>" +
                    "<body><p>登录成功</p></body>" +
                    "</html>");

            writer.close();



        }else{
            response.sendRedirect("/html/login.html");
        }

    }
}
